// 操作日志页面JS
// 依赖：页面有id=logList

let currentPage = 1;
let totalPages = 1;
let totalRecords = 0;
const perPage = 50;

document.addEventListener('DOMContentLoaded', function () {
  // 初始化页面
  loadLogs();
  
  // 绑定事件
  bindEvents();
});

function bindEvents() {
  // 筛选按钮
  document.getElementById('filterBtn').addEventListener('click', function() {
    currentPage = 1;
    loadLogs();
  });
  
  // 重置筛选按钮
  document.getElementById('resetFilterBtn').addEventListener('click', function() {
    document.getElementById('actionFilter').value = '';
    document.getElementById('startDate').value = '';
    document.getElementById('endDate').value = '';
    currentPage = 1;
    loadLogs();
  });
  
  // 分页按钮
  document.getElementById('prevPage').addEventListener('click', function() {
    if (currentPage > 1) {
      currentPage--;
      loadLogs();
    }
  });
  
  document.getElementById('nextPage').addEventListener('click', function() {
    if (currentPage < totalPages) {
      currentPage++;
      loadLogs();
    }
  });
  
  // 模态框关闭
  const modal = document.getElementById('logDetailModal');
  const closeBtn = modal.querySelector('.close');
  closeBtn.addEventListener('click', function() {
    modal.style.display = 'none';
  });
  
  // 点击模态框外部关闭
  window.addEventListener('click', function(event) {
    if (event.target === modal) {
      modal.style.display = 'none';
    }
  });
}

function loadLogs() {
  const logList = document.getElementById('logList');
  const token = localStorage.getItem('access_token') || '';
  
  // 构建查询参数
  const params = new URLSearchParams({
    page: currentPage,
    per_page: perPage
  });
  
  const actionFilter = document.getElementById('actionFilter').value;
  const startDate = document.getElementById('startDate').value;
  const endDate = document.getElementById('endDate').value;
  
  if (actionFilter) {
    params.append('action', actionFilter);
  }
  if (startDate) {
    params.append('start_date', startDate);
  }
  if (endDate) {
    params.append('end_date', endDate);
  }
  
  fetch(`/api/admin/logs?${params.toString()}`, {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer ' + token
    }
  })
    .then(res => {
      if (res.status === 401 || res.status === 403) {
        window.location.href = '/login';
        return Promise.reject('未认证');
      }
      return res.json();
    })
    .then(data => {
      if (!data.success) {
        alert(data.message || data.msg || '获取日志失败');
        return;
      }
      
      // 更新分页信息
      updatePagination(data.pagination);
      
      // 渲染日志列表
      renderLogList(data.data || []);
    })
    .catch(err => {
      if (err !== '未认证') {
        console.error('请求失败:', err);
        alert('请求失败: ' + err);
      }
    });
}

function updatePagination(pagination) {
  currentPage = pagination.page;
  totalPages = pagination.pages;
  totalRecords = pagination.total;
  
  const startRecord = (currentPage - 1) * perPage + 1;
  const endRecord = Math.min(currentPage * perPage, totalRecords);
  
  document.getElementById('startRecord').textContent = startRecord;
  document.getElementById('endRecord').textContent = endRecord;
  document.getElementById('totalRecords').textContent = totalRecords;
  document.getElementById('currentPage').textContent = `第 ${currentPage} 页`;
  
  // 更新分页按钮状态
  document.getElementById('prevPage').disabled = currentPage <= 1;
  document.getElementById('nextPage').disabled = currentPage >= totalPages;
}

function renderLogList(logs) {
  const logList = document.getElementById('logList');
  logList.innerHTML = '';
  
  if (logs.length === 0) {
    logList.innerHTML = '<tr><td colspan="5" class="text-center">暂无日志记录</td></tr>';
    return;
  }
  
  logs.forEach(log => {
    const tr = document.createElement('tr');
    const actionBadge = getActionBadge(log.action);
    
    tr.innerHTML = `
      <td>${log.username || '未知用户'}</td>
      <td>${actionBadge}</td>
      <td>${log.detail || ''}</td>
      <td>${formatDateTime(log.operation_time)}</td>
      <td>
        <button class="btn btn-sm btn-outline-primary" onclick="viewLogDetail(${log.id})">详情</button>
        ${getRestoreButton(log)}
      </td>
    `;
    logList.appendChild(tr);
  });
}

function getActionBadge(action) {
  const actionText = {
    'CREATE': '创建',
    'UPDATE': '更新', 
    'DELETE': '删除',
    'RESTORE': '恢复'
  };
  
  return `<span class="log-action-badge log-action-${action}">${actionText[action] || action}</span>`;
}

function getRestoreButton(log) {
  // 只有删除操作和更新操作可以恢复
  if (log.action === 'DELETE') {
    return `<button class="btn btn-sm btn-outline-success" onclick="restoreLog(${log.id})">恢复</button>`;
  } else if (log.action === 'UPDATE' && log.old_content) {
    return `<button class="btn btn-sm btn-outline-warning" onclick="restoreLog(${log.id})">恢复此版本</button>`;
  }
  return '';
}

function formatDateTime(dateTimeStr) {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return date.toLocaleString('zh-CN');
}

function viewLogDetail(logId) {
  const token = localStorage.getItem('access_token') || '';
  
  fetch(`/api/admin/logs/${logId}`, {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer ' + token
    }
  })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        showLogDetailModal(data.data);
      } else {
        alert(data.message || '获取日志详情失败');
      }
    })
    .catch(err => {
      console.error('获取日志详情失败:', err);
      alert('获取日志详情失败: ' + err);
    });
}

function showLogDetailModal(log) {
  const modal = document.getElementById('logDetailModal');
  const content = document.getElementById('logDetailContent');
  const restoreContainer = document.getElementById('restoreButtonContainer');
  
  let detailHtml = `
    <div class="row">
      <div class="col-md-6">
        <p><strong>操作用户:</strong> ${log.username || '未知用户'}</p>
        <p><strong>操作类型:</strong> ${getActionBadge(log.action)}</p>
        <p><strong>操作时间:</strong> ${formatDateTime(log.operation_time)}</p>
        <p><strong>IP地址:</strong> ${log.ip_address || '未知'}</p>
      </div>
      <div class="col-md-6">
        <p><strong>目标ID:</strong> ${log.target_id || '无'}</p>
        <p><strong>操作详情:</strong> ${log.detail || '无'}</p>
      </div>
    </div>
  `;
  
  // 显示新数据
  if (log.new_content) {
    try {
      const newData = JSON.parse(log.new_content);
      detailHtml += `
        <div class="mt-3">
          <h5>新数据:</h5>
          <pre class="bg-light p-2 rounded">${JSON.stringify(newData, null, 2)}</pre>
        </div>
      `;
    } catch (e) {
      detailHtml += `
        <div class="mt-3">
          <h5>新数据:</h5>
          <pre class="bg-light p-2 rounded">${log.new_content}</pre>
        </div>
      `;
    }
  }
  
  // 显示旧数据
  if (log.old_content) {
    try {
      const oldData = JSON.parse(log.old_content);
      detailHtml += `
        <div class="mt-3">
          <h5>旧数据:</h5>
          <pre class="bg-light p-2 rounded">${JSON.stringify(oldData, null, 2)}</pre>
        </div>
      `;
    } catch (e) {
      detailHtml += `
        <div class="mt-3">
          <h5>旧数据:</h5>
          <pre class="bg-light p-2 rounded">${log.old_content}</pre>
        </div>
      `;
    }
  }
  
  content.innerHTML = detailHtml;
  
  // 显示恢复按钮
  restoreContainer.innerHTML = '';
  if (log.action === 'DELETE') {
    restoreContainer.innerHTML = `
      <button class="btn btn-success" onclick="restoreLog(${log.id})">
        恢复已删除的记录
      </button>
    `;
  } else if (log.action === 'UPDATE' && log.old_content) {
    restoreContainer.innerHTML = `
      <button class="btn btn-warning" onclick="restoreLog(${log.id})">
        恢复到此版本
      </button>
    `;
  }
  
  modal.style.display = 'block';
}

function restoreLog(logId) {
  if (!confirm('确定要恢复此记录吗？')) {
    return;
  }
  
  const token = localStorage.getItem('access_token') || '';
  
  fetch(`/api/admin/logs/${logId}/restore`, {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer ' + token,
      'Content-Type': 'application/json'
    }
  })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        alert('恢复成功');
        // 关闭模态框
        document.getElementById('logDetailModal').style.display = 'none';
        // 重新加载日志列表
        loadLogs();
      } else {
        alert('恢复失败: ' + (data.message || '未知错误'));
      }
    })
    .catch(err => {
      console.error('恢复失败:', err);
      alert('恢复失败: ' + err);
    });
}
